import React, { useState } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';

const getBase64 = (img: any, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};

export default function dynamic(props: any) {
    const { url, type, size } = props
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    const isVideo = type[0] === 'video/mp4' 

    const beforeUpload = (file: any) => {
        console.log(file.type)
        // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        const isJpgOrPng = type.some((item: any) => item === file.type)
        if (!isJpgOrPng) {
            message.error('必须上传jpg或者是png后缀!');
        }
        // 大小按照B来算   10KB  
        const isLt5M = file.size / 1024 / 1024 < size;
        if (!isLt5M) {
            message.error(`图片大小不能超过${size}M!`);
        }
        return isJpgOrPng && isLt5M;
    };

    const handleChange: any = (info: any) => {
        // info  
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }

        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, (url) => {
                setLoading(false);
                setImageUrl(url);
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    return (
        <div>
            {/* 1. 请求地址自定义   2. 上传类型    3. 大小 */}
            <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                // 上传地址  
                action={url}
                //  点击确定上传的时候会执行  文件类型  大小
                beforeUpload={beforeUpload}
                // 
                onChange={handleChange}
            >   
                { isVideo? <video style={{
                    width: 102,
                    height: 102
                }} src={imageUrl}/>: imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
        </div>
    )
}
